<!--
 * @copyright 2025 银杏ERP
 * @author 银杏ERP
 * @version 1.0
 * @license http://www.hhyx.xyz
 * @developer Lhf
-->

<template>
  <div class="sales-order-list-card">
    <div class="card-header">
      <div class="header-left">
        <Icon name="fa fa-file-text-o" class="header-icon" />
        <h3 class="card-title">销售订单</h3>
      </div>
      <div class="header-actions">
        <el-tooltip content="新建订单" placement="top">
          <el-button type="primary" class="gradient-button-blue" size="small" @click="createOrder">
            <Icon name="fa fa-plus" />
          </el-button>
        </el-tooltip>
        <el-button type="primary" class="gradient-button-purple" size="small" @click="viewAllOrders">
          <Icon name="fa fa-list-ul" class="icon-margin" /> 查看全部
        </el-button>
      </div>
    </div>
    
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="搜索订单号/客户/销售员" 
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <Icon name="fa fa-search" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.date"
            type="date"
            placeholder="选择日期"
            :clearable="true"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="订单状态" clearable>
            <el-option label="全部状态" value="" />
            <el-option label="已完成" value="completed" />
            <el-option label="处理中" value="pending" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="gradient-button-green" @click="handleSearch">
            <Icon name="fa fa-search" class="icon-margin" /> 搜索
          </el-button>
          <el-button type="info" plain @click="resetSearch">
            <Icon name="fa fa-refresh" class="icon-margin" /> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="order-table">
      <el-table 
        :data="orders.data" 
        style="width: 100%" 
        :border="false"
        v-loading="loading"
        row-key="id"
        @row-click="handleRowClick"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="order-detail-expand">
              <div class="order-products">
                <div class="detail-title">
                  <Icon name="fa fa-cubes" class="icon-margin" /> 订单商品
                </div>
                <el-table :data="props.row.products || []" size="small" border>
                  <el-table-column label="商品编号" prop="id" width="100" />
                  <el-table-column label="商品名称" prop="name" min-width="150" show-overflow-tooltip />
                  <el-table-column label="数量" prop="quantity" width="80" align="right" />
                  <el-table-column label="单价" width="120" align="right">
                    <template #default="scope">
                      {{ formatCurrency(scope.row.price) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="小计" width="120" align="right">
                    <template #default="scope">
                      {{ formatCurrency(scope.row.price * scope.row.quantity) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <div class="order-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  class="gradient-button-blue" 
                  @click.stop="viewOrderDetail(props.row)"
                >
                  <Icon name="fa fa-eye" class="icon-margin" /> 查看详情
                </el-button>
                <el-button 
                  type="success" 
                  size="small" 
                  class="gradient-button-green" 
                  v-if="props.row.status === 'pending'"
                  @click.stop="approveOrder(props.row)"
                >
                  <Icon name="fa fa-check" class="icon-margin" /> 审核通过
                </el-button>
                <el-button 
                  type="warning" 
                  size="small" 
                  class="gradient-button-orange" 
                  v-if="props.row.status === 'pending'"
                  @click.stop="rejectOrder(props.row)"
                >
                  <Icon name="fa fa-times" class="icon-margin" /> 驳回
                </el-button>
                <el-button 
                  type="info" 
                  size="small" 
                  plain
                  @click.stop="printOrder(props.row)"
                >
                  <Icon name="fa fa-print" class="icon-margin" /> 打印
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column width="60" align="center">
          <template #default="scope">
            <el-tag
              size="small"
              effect="dark"
              class="priority-tag"
              :type="scope.row.priority === 3 ? 'danger' : (scope.row.priority === 2 ? 'warning' : 'info')"
            >
              {{ getOrderPriorityLabel(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="id" label="订单号" width="140">
          <template #default="scope">
            <span class="order-id">{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="日期" width="110" />
        <el-table-column prop="customerName" label="客户名称" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <div class="customer-info">
              <span class="customer-name">{{ scope.row.customerName }}</span>
              <el-tooltip :content="getCustomerDetail(scope.row)" placement="top" :show-after="500">
                <span class="info-icon-wrapper">
                  <Icon name="fa fa-info-circle" class="info-icon" />
                </span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="salesperson" label="销售员" width="100" />
        <el-table-column label="商品数" width="80" align="center">
          <template #default="scope">
            <el-badge :value="scope.row.products?.length || 0" type="primary" />
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="订单金额" width="120" align="right">
          <template #default="scope">
            <span class="amount" :class="{'high-value': scope.row.amount > 10000}">
              {{ formatCurrency(scope.row.amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="getPaymentStatusType(scope.row.paymentStatus)"
              size="small"
              effect="light"
            >
              {{ getPaymentStatusText(scope.row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              size="small"
              effect="light"
              :type="scope.row.status === 'completed' ? 'success' : (scope.row.status === 'pending' ? 'warning' : (scope.row.status === 'cancelled' ? 'danger' : (scope.row.status === 'shipping' ? 'primary' : 'info')))"
            >
              {{ getOrderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <div class="table-actions">
              <el-tooltip content="查看详情" placement="top">
                <div class="action-wrapper">
                  <el-button size="small" type="primary" class="action-button" link @click.stop="viewOrderDetail(scope.row)">
                    <Icon name="fa fa-eye" />
                  </el-button>
                </div>
              </el-tooltip>
              <el-tooltip content="编辑订单" placement="top">
                <div class="action-wrapper">
                  <el-button size="small" type="primary" class="action-button" link @click.stop="editOrder(scope.row)">
                    <Icon name="fa fa-edit" />
                  </el-button>
                </div>
              </el-tooltip>
              <el-tooltip content="跟踪物流" placement="top" v-if="scope.row.status === 'completed'">
                <div class="action-wrapper">
                  <el-button size="small" type="primary" class="action-button" link @click.stop="trackOrder(scope.row)">
                    <Icon name="fa fa-truck" />
                  </el-button>
                </div>
              </el-tooltip>
              <el-tooltip content="复制订单" placement="top">
                <div class="action-wrapper">
                  <el-button size="small" type="primary" class="action-button" link @click.stop="duplicateOrder(scope.row)">
                    <Icon name="fa fa-copy" />
                  </el-button>
                </div>
              </el-tooltip>
              <el-dropdown trigger="click" @click.stop @command="handleCommand($event, scope.row)">
                <div class="action-wrapper">
                  <el-button size="small" type="primary" class="action-button" link>
                    <Icon name="fa fa-ellipsis-v" />
                  </el-button>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="print">打印订单</el-dropdown-item>
                    <el-dropdown-item command="export">导出订单</el-dropdown-item>
                    <el-dropdown-item command="cancel" v-if="scope.row.status === 'pending'">取消订单</el-dropdown-item>
                    <el-dropdown-item command="delete" divided type="danger">删除订单</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="table-footer">
        <span class="record-count">共 {{ orders.total }} 条记录</span>
        <el-pagination
          background
          layout="prev, pager, next, sizes"
          :total="orders.total"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, PropType, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Icon from '/@/components/icon/index.vue'

interface OrderProduct {
  id: string
  name: string
  quantity: number
  price: number
}

interface OrderItem {
  id: string
  date: string
  customerName: string
  amount: number
  salesperson: string
  status: string
  paymentStatus?: string
  priority?: number
  products?: OrderProduct[]
}

interface OrdersData {
  total: number
  data: OrderItem[]
}

const props = defineProps({
  orders: {
    type: Object as PropType<OrdersData>,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['view-all', 'search'])

// 分页相关
const pageSize = ref(10)
const currentPage = ref(1)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  date: '',
  status: ''
})

// 重置搜索条件
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.date = ''
  searchForm.status = ''
  handleSearch()
}

// 查看全部订单
const viewAllOrders = () => {
  emit('view-all')
}

// 创建新订单
const createOrder = () => {
  ElMessage.success('跳转到创建订单页面')
}

// 处理搜索
const handleSearch = () => {
  emit('search', {
    keyword: searchForm.keyword,
    date: searchForm.date,
    status: searchForm.status,
    page: currentPage.value,
    pageSize: pageSize.value
  })
}

// 改变每页记录数
const handleSizeChange = (size: number) => {
  pageSize.value = size
  handleSearch()
}

// 改变页码
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  handleSearch()
}

// 处理行点击
const handleRowClick = (row: OrderItem) => {
  // 这里可以通过路由导航到订单详情页
  console.log('点击了订单:', row.id)
}

// 查看订单详情
const viewOrderDetail = (row: OrderItem) => {
  ElMessage.success(`查看订单详情: ${row.id}`)
}

// 编辑订单
const editOrder = (row: OrderItem) => {
  ElMessage.success(`编辑订单: ${row.id}`)
}

// 跟踪订单
const trackOrder = (row: OrderItem) => {
  ElMessage.success(`跟踪订单物流: ${row.id}`)
}

// 复制订单
const duplicateOrder = (row: OrderItem) => {
  ElMessage.success(`复制订单: ${row.id}`)
}

// 审核通过订单
const approveOrder = (row: OrderItem) => {
  ElMessageBox.confirm(
    `确定要审核通过订单 ${row.id} 吗？`,
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    ElMessage.success(`订单 ${row.id} 已审核通过`)
  }).catch(() => {})
}

// 驳回订单
const rejectOrder = (row: OrderItem) => {
  ElMessageBox.confirm(
    `确定要驳回订单 ${row.id} 吗？`,
    '驳回确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      inputPlaceholder: '请输入驳回原因'
    }
  ).then(() => {
    ElMessage.warning(`订单 ${row.id} 已驳回`)
  }).catch(() => {})
}

// 打印订单
const printOrder = (row: OrderItem) => {
  ElMessage.success(`打印订单: ${row.id}`)
}

// 处理下拉菜单命令
const handleCommand = (command: string, row: OrderItem) => {
  switch (command) {
    case 'print':
      printOrder(row)
      break
    case 'export':
      ElMessage.success(`导出订单: ${row.id}`)
      break
    case 'cancel':
      ElMessageBox.confirm(
        `确定要取消订单 ${row.id} 吗？`,
        '取消确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        ElMessage.warning(`订单 ${row.id} 已取消`)
      }).catch(() => {})
      break
    case 'delete':
      ElMessageBox.confirm(
        `确定要删除订单 ${row.id} 吗？此操作不可恢复！`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }
      ).then(() => {
        ElMessage.error(`订单 ${row.id} 已删除`)
      }).catch(() => {})
      break
  }
}

// 获取订单状态文本
const getOrderStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'completed': '已完成',
    'pending': '处理中',
    'cancelled': '已取消',
    'shipping': '配送中',
    'returned': '已退货'
  }
  return statusMap[status] || '待处理'
}

// 获取支付状态类型
const getPaymentStatusType = (status: string | undefined): string => {
  if (!status) return 'info'
  
  const typeMap: Record<string, string> = {
    'paid': 'success',
    'unpaid': 'info',
    'partial': 'warning',
    'refunded': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取支付状态文本
const getPaymentStatusText = (status: string | undefined): string => {
  if (!status) return '待支付'
  
  const statusMap: Record<string, string> = {
    'paid': '已支付',
    'unpaid': '待支付',
    'partial': '部分支付',
    'refunded': '已退款'
  }
  return statusMap[status] || '待支付'
}

// 获取订单优先级标签
const getOrderPriorityLabel = (priority: number | undefined): string => {
  if (!priority) return '普通'
  if (priority === 3) return '紧急'
  if (priority === 2) return '高'
  return '普通'
}

// 获取客户详情
const getCustomerDetail = (row: OrderItem): string => {
  return `${row.customerName}\n联系人: 联系人信息\n电话: 联系电话`
}

// 表格行样式
const tableRowClassName = ({ row }: { row: OrderItem }) => {
  if (row.status === 'cancelled') return 'cancelled-row'
  if (row.priority === 3) return 'urgent-row'
  return ''
}

// 格式化货币
const formatCurrency = (value: number) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(value)
}
</script>

<style scoped lang="scss">
.sales-order-list-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  height: 100%;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .header-left {
      display: flex;
      align-items: center;
      
      .header-icon {
        color: #409EFF;
        font-size: 18px;
        margin-right: 10px;
      }
      
      .card-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          left: 0;
          bottom: -5px;
          width: 30px;
          height: 3px;
          background: linear-gradient(to right, #36D1DC, #5B86E5);
          border-radius: 3px;
        }
      }
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .search-bar {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
    transition: all 0.3s;
    
    &:hover {
      background-color: #f0f2f5;
      box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    }
    
    .el-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      justify-content: space-between;
      
      .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        flex: 1;
        min-width: 180px;
      }
    }
  }
  
  .order-table {
    :deep(.el-table) {
      border-radius: 8px;
      overflow: hidden;
      
      th {
        font-weight: 600;
        background-color: #f5f7fa !important;
      }
      
      .cancelled-row {
        background-color: rgba(245, 108, 108, 0.1);
        color: #909399;
        
        td {
          text-decoration: line-through;
        }
      }
      
      .urgent-row {
        background-color: rgba(245, 108, 108, 0.05);
      }
      
      .el-table__row {
        transition: all 0.3s;
        
        &:hover {
          background-color: #f8f9fa !important;
          transform: translateY(-2px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          z-index: 2;
          position: relative;
        }
      }
    }
    
    .order-id {
      color: #409EFF;
      font-weight: 500;
      transition: all 0.3s;
      
      &:hover {
        color: #66b1ff;
        text-decoration: underline;
      }
    }
    
    .customer-info {
      display: flex;
      align-items: center;
      
      .customer-name {
        margin-right: 5px;
      }
      
      .info-icon-wrapper {
        display: inline-block;
        cursor: help;
        
        .info-icon {
          color: #909399;
          font-size: 14px;
        }
      }
    }
    
    .amount {
      font-weight: 500;
      
      &.high-value {
        color: #F56C6C;
        font-weight: 600;
      }
    }
    
    .priority-tag {
      width: 16px;
      height: 16px;
      padding: 0;
      border-radius: 50%;
      display: inline-block;
    }
    
    .table-actions {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 5px;
      
      .action-wrapper {
        display: inline-block;
      }
      
      .action-button {
        padding: 4px;
        font-size: 14px;
      }
    }
    
    .order-detail-expand {
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 8px;
      margin: 10px;
      
      .order-products {
        margin-bottom: 15px;
        
        .detail-title {
          font-weight: 600;
          font-size: 14px;
          margin-bottom: 10px;
          color: #606266;
        }
      }
      
      .order-actions {
        display: flex;
        gap: 10px;
        margin-top: 15px;
        justify-content: flex-end;
      }
    }
    
    .table-footer {
      margin-top: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .record-count {
        font-size: 13px;
        color: #909399;
      }
    }
  }
  
  // 渐变按钮样式
  .gradient-button-blue {
    background: linear-gradient(to right, #36D1DC, #5B86E5);
    border: none;
    color: white;
    
    &:hover {
      background: linear-gradient(to right, #5B86E5, #36D1DC);
    }
  }
  
  .gradient-button-green {
    background: linear-gradient(to right, #67B26F, #4ca2cd);
    border: none;
    color: white;
    
    &:hover {
      background: linear-gradient(to right, #4ca2cd, #67B26F);
    }
  }
  
  .gradient-button-orange {
    background: linear-gradient(to right, #FF9966, #FF5E62);
    border: none;
    color: white;
    
    &:hover {
      background: linear-gradient(to right, #FF5E62, #FF9966);
    }
  }
  
  .gradient-button-purple {
    background: linear-gradient(to right, #8E2DE2, #4A00E0);
    border: none;
    color: white;
    
    &:hover {
      background: linear-gradient(to right, #4A00E0, #8E2DE2);
    }
  }
  
  .icon-margin {
    margin-right: 5px;
  }
}

// 响应式调整
@media screen and (max-width: 1200px) {
  .sales-order-list-card {
    .search-bar {
      .el-form {
        .el-form-item {
          min-width: 160px;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .sales-order-list-card {
    padding: 15px;
    
    .search-bar {
      padding: 10px;
      
      .el-form {
        flex-direction: column;
        
        .el-form-item {
          margin-bottom: 10px;
          width: 100%;
        }
      }
    }
    
    .table-footer {
      flex-direction: column;
      gap: 10px;
      align-items: center;
      
      .record-count {
        margin-bottom: 10px;
      }
    }
  }
}
</style> 